const { Base } = require('../utils');


module.exports = class extends Base {
  constructor(args, opts) {
    super(args, opts);

    this.option("spidersFolder", {
      description: 'The "spiders/" directory in scrapy project',
      type: String,
      hide: false,
    });
  }
  
  initializing() {
    this.projectPath = process.cwd();
    this.projectName = Base.getFolderName(this.projectPath);

    const configFilePath1 = Base.getAbsolutePath(this.projectPath, Base.SCRAPY_CONFIG_FILE);
    const configFilePath2 = Base.getAbsolutePath(this.projectPath, '..', Base.SCRAPY_CONFIG_FILE);
    
    if (this.options.spidersFolder) {
      this.spiderFolder = this.options.spidersFolder;
    } else {
      if (Base.existsPath(configFilePath1)) {
        this.spiderFolder = Base.getAbsolutePath(this.projectPath, this.projectName, Base.SPIDERS);
      } else if (Base.existsPath(configFilePath2)) {
        this.spiderFolder = Base.getAbsolutePath(this.projectPath, Base.SPIDERS);
      } else {
        this.log.error(`You are not in a scrapy project folder.`);
        process.exit(1);
      }
    }
  }
  
  async prompting() {
    this.answers = await this.prompt([
      {
        type: 'input',
        name: 'spider_name',
        message: 'Spider name',
        validate: spider_name => {
          if (spider_name && Base.existsPath(Base.getAbsolutePath(this.spiderFolder, `${spider_name}${Base.PY_EXT}`))) {
            return `The spider "${spider_name}" has already existed.`;
          }
          return Base.validationName(spider_name);
        },
      },
      {
        type: 'list',
        name: 'spiderTmplName',
        message: 'Spider template',
        choices: Base.TMPL_SPIDER_NAMES,
        loop: false,
      },
      {
        type: 'input',
        name: 'domain',
        message: 'Domain',
        validate: Base.validationDomain,
      },
    ]);

    this.answers.spiderName = Base.stringCamelcase(this.answers.spider_name);
  }

  writing() {
    // 复制 spider 模板文件
    const from = this.destinationPath(Base.TMPL_SPIDER_ROOT, `${this.answers.spiderTmplName}${Base.TMPL_EXT}`);
    const to = this.destinationPath(this.spiderFolder, `${this.answers.spider_name}${Base.PY_EXT}`);
    this.fs.copyTpl(from, to, this.answers);
  }
}